<template>
    <div class="layout01-main">
        <div class="move-box">
            <RiskLeftModule02
                :treeData="treeData"
                leftHeight="100%"
                :default-expanded-keys="['-1']"
                :default-checked-keys="['-1']"
                @on-handleNode="clickLeftNode($event, false, 1)"
            >
                <template slot="ltitle">分组信息</template>
            </RiskLeftModule02>
            <RiskRightModule02>
                <p slot="rtitle">明细</p>
                <span slot="button" class="layout01-r-slot">
                    <el-button v-show="showDetail === '1'  || showDetail === '3'" type="primary" size="mini" v-authCode="B_0107" @click="searchVisibe = true">查询</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0103" type="primary" size="mini" @click="handleTabs('add')">新增</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0104" type="danger" size="mini" @click="onOpenDelModal">删除</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0405" type="primary" size="mini" @click="onOpenEnable">启用</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0406" type="danger" size="mini" @click="onOpenDisabled">禁用</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0135" type="primary" size="mini" @click="exportFile('sql')">导出SQL</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0135" type="primary" size="mini" @click="exportFile('pdf')">导出PDF</el-button>
                    <el-button v-show="showDetail === '1'" v-authCode="B_0135" type="primary" size="mini" @click="exportFile('json')">导出JSON</el-button>
                    <el-input
                        v-show="showDetail === '2'"
                        v-model="searchClassName"
                        size="mini"
                        style="width: 200px; margin-right: 10px"
                        placeholder="名称"
                    ></el-input>
                    <el-button v-show="showDetail === '2'" v-authCode="B_0107" type="primary" size="mini" @click="getListClassByName">
                        查 询
                    </el-button>
                    <el-button
                        v-show="showDetail === '2' || (showDetail === '3' && classLevel != '3')"
                        type="primary"
                        size="mini"
                        @click="newlyVisible = true"
                        >新增分类</el-button
                    >
                    <el-button v-show="showDetail === '2'" v-authCode="B_0104" type="danger" size="mini" @click="delRows">删除</el-button>

                    <el-button v-show="showDetail == '3' && selectedNode.id != '3'" type="primary" size="mini" @click="handleEdit">编辑</el-button>
                </span>
                <slot>
                    <el-table
                        v-if="showDetail === '1' || showDetail === '3'"
                        :data="getCurrentPageTableData"
                        style="width: 100%;"
                        height="calc(100vh - 200px)"
                        size="mini"
                        v-loading="loading"
                        v-table-top="paging.currentPage"
                        border
                    >
                        <RiskTableSelection
                            row-key="key"
                            :current-page-table-list="getCurrentPageTableData"
                            :selected="tableSelectedList"
                            :drop-down-list="[
                                { text: '选择全部页', value: 'all' },
                                { text: '选择当前页', value: 'current' },
                            ]"
                            show-drop-down
                            @dropdown-click="dropdownClick"
                        />
                        <el-table-column prop="entryCalculateFactorCode" label="因子编码" width="110"> </el-table-column>
                        <el-table-column prop="entryCalculateFactorName" label="因子名称" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="riskCalTypesText" label="作用范围" width="180" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="changeTypeText" label="变动类型" width="150" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="entryTypesText" label="风险类型" width="150" show-overflow-tooltip> </el-table-column>
                        <el-table-column label="状态" width="80">
                            <template slot-scope="scope">
                                <span v-if="scope.row.validSymbol === '1'" style="color: green">启用</span>
                                <span v-else style="color: red">禁用</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="数据源配置" width="100">
                            <template slot-scope="scope">
                                <span v-if="scope.row.dataSourceSymbol === '1'" style="color: green">已配置</span>
                                <span v-else style="color: red">无配置</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-view"
                                    v-authCode="B_0105"
                                    @on-click="handleTabs('look', scope.row)"
                                    topTitle="计算因子详情"
                                />
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-edit"
                                    v-authCode="B_0106"
                                    @on-click="handleTabs('edit', scope.row)"
                                    topTitle="编辑明细"
                                />
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-switch-button"
                                    topTitle="数据源设置"
                                    v-authCode="B_0021"
                                    @on-click="openDataSource(scope.row)"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block" v-show="showDetail === '1' || showDetail === '3'">
                        <risk-pagination :paging="paging" @page-change="currentChange"></risk-pagination>
                    </div>

                    <RiskTablePlus
                        v-if="showDetail === '2'"
                        style="height: calc(100vh - 200px)"
                        ref="risk-table"
                        :tableData="tableData2"
                        :tableConfig="tableConfig2"
                        :column="columns"
                    >
                        <template #operation="{ row }">
                            <RiskIconButton
                                :disabled="row.classID == 3"
                                type="primary"
                                icon="el-icon-edit"
                                topTitle="编辑"
                                @on-click="editRow(row)"
                            ></RiskIconButton>
                            <RiskIconButton
                                :disabled="row.classID == 3"
                                type="danger"
                                icon="el-icon-delete"
                                topTitle="删除"
                                size="mini"
                                @on-click="delRow(row)"
                            ></RiskIconButton>
                        </template>
                    </RiskTablePlus>
                    <div v-show="showDetail === '2'" class="block">
                        <el-pagination
                            background
                            @current-change="currentChange2"
                            layout="total, prev, pager, next"
                            :total="paging2.total"
                            :page-size="paging2.pageSize"
                            :current-page.sync="paging2.currentPage"
                        >
                        </el-pagination>
                    </div>
                </slot>
            </RiskRightModule02>
        </div>
        <yh-dialog drag title="确认删除以下分类" :visible.sync="delRowVisible" width="500px" :close-on-click-modal="false">
            <div>
                <p>{{ checkRowKeysName.join('，') }}</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="delRowVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleDelRow">确 定</el-button>
            </div>
        </yh-dialog>
        <!-- 新增分类 -->
        <yh-dialog drag title="新增分类" :visible.sync="newlyVisible" width="500px" :close-on-click-modal="false">
            <div>
                <el-form label-width="100px" style="margin-top: 10px">
                    <el-form-item label="分类名称:">
                        <el-input v-model="newClassName" :maxlength="50" size="mini" placeholder="请输入分类名称" style="width: 90%"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="newlyVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleAddNewly">确 定</el-button>
            </div>
        </yh-dialog>
        <yh-dialog v-if="visibleTemp" drag title="" :visible.sync="visibleTemp" width="740px" :close-on-click-modal="false">
            <RiskTrantableInline
                style="height: 500px"
                ref="trans"
                url="/original/factor/factorList"
                index-key="entryCalculateFactorCode"
                left-placeholder="编号/名称"
                right-placeholder="编号/名称"
                :columns="columns3"
                :right-table-data="selected"
                :search-names="['entryCalculateFactorCode', 'entryCalculateFactorName']"
            />
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="visibleTemp = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
            </div>
        </yh-dialog>
        <!-- 编辑分类 -->
        <yh-dialog drag title="编辑分类" :visible.sync="editVisible" width="500px" :close-on-click-modal="false">
            <div>
                <el-form label-width="100px" style="margin-top: 10px">
                    <el-form-item label="分类名称:">
                        <el-input v-model="rowData.className" :maxlength="50" size="mini" placeholder="请输入分类名称" style="width: 90%"></el-input>
                    </el-form-item>
                    <el-form-item label="排序级别:">
                        <el-input-number :min="1" v-model="rowData.order" size="mini" placeholder="请输入排序级别" style="width: 90%" controls-position="right"></el-input-number>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="editVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleEditNewly">确 定</el-button>
            </div>
        </yh-dialog>
        <!--    搜索弹窗    -->
        <CalculateFactorSearch :visible.sync="searchVisibe" @on-submit="onSearch" :search-data="searchParam" />
        <!--    禁用弹窗    -->
        <CalculateFactorDisabled :visible.sync="disabledVisible" :list="disabledModalData.list" @on-submit="disabledOnSubmit" />
        <!--    启动弹窗    -->
        <CalculateFactorEnable :visible.sync="enableVisible" :list="enableModalData.list" @on-submit="enableOnSubmit" />
        <!--    删除弹窗    -->
        <CalculateFactorDelete :visible.sync="delVisible" :list="delModalData.list" @on-submit="delOnSubmit" />
        <!--   导出SQL弹窗   -->
        <CalculateFactorExportsql :visible.sync="exportVisible" :list="exportModalData.list" @on-submit="exportSqlOnSubmit" />
        <!--   数据源设置弹窗   -->
        <CalculateFactorDatasource :visible.sync="showSourceModal" :code="sourceCode" @on-submit="sourceOnSubmit" />
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import { getFactorListByPs, checkBoundOrFactorIsUsed, exportFactorToPDF, exportFactorToJson, getDataSourceByCodes } from '@/pages/quota/api';
import { getCurrentPageData } from '@/utils/tools';
import DictionConstUtil from '@/utils/diction-const-util';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';

// import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import RiskLeftModule02 from '@/common/components/risk-left-module02.vue';
import RiskRightModule02 from '@/common/components/risk-right-module02.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTablePlus from '@/common/components/risk-table-plus.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';

import CalculateFactorSearch from '@/pages/quota/calculate-factor/calculate-factor-search.vue';
import CalculateFactorDisabled from '@/pages/quota/calculate-factor/calculate-factor-disabled.vue';
import CalculateFactorEnable from '@/pages/quota/calculate-factor/calculate-factor-enable.vue';
import CalculateFactorDelete from '@/pages/quota/calculate-factor/calculate-factor-delete.vue';
import CalculateFactorExportsql from '@/pages/quota/calculate-factor/calculate-factor-exportsql.vue';
import CalculateFactorDatasource from '@/pages/quota/calculate-factor/calculate-factor-datasource.vue';
import RiskTrantableInline from '@/common/components/risk-trantable-inline.vue';

@Component({
    name: 'CalculateFactorTable',
    components: {
        CalculateFactorEnable,
        RiskLeftModule02,
        RiskRightModule02,
        RiskIconButton,
        CalculateFactorSearch,
        CalculateFactorDisabled,
        CalculateFactorDelete,
        CalculateFactorExportsql,
        CalculateFactorDatasource,
        RiskPagination,
        RiskTablePlus,
        RiskTrantableInline
    },
})
export default class CalculateFactorTable extends mixins(RiskEmitter) {
    mounted() {
        this.clickLeftNode(this.selectedNode, true, 1);
        this.$on('refreshPage', page => {
            this.clickLeftNode(this.selectedNode, true, this.paging.currentPage, false);
        });
        this.getFactorTree();
    }

    private loading = false;
    private DictionConstUtil = DictionConstUtil;
    // 左侧数据
    private selectedNode = { label: '全部选择', id: '-1' };
    private treeData = [
        {
            label: '全部选择',
            id: '-1',
            children: [
                {
                    label: '产品指标',
                    id: '0',
                },
                {
                    label: '项目指标',
                    id: '1',
                },
                {
                    label: '自定义分类',
                    id: '2',
                    children: [],
                },
            ],
        },
    ];
    // 右边数据
    private tableData: any[] = [];
    private tableDataCache: any[] = [];
    private tableSelectedList: any[] = [];
    private paging = { total: 0, currentPage: 1, pageSize: 50 };

    // 搜索弹窗
    private searchVisibe: boolean = false;
    private searchParam = {
        entryCalculateFactorCode: '',
        entryCalculateFactorName: '',
        changeType: '',
        riskCalType: '',
        validSymbol: '',
        entryType: '',
    };

    // 禁用弹窗
    private disabledVisible = false;
    private disabledModalData = {
        visible: false,
        list: [],
    };

    // 启用弹窗
    private enableVisible = false;
    private enableModalData = {
        visible: false,
        list: [],
    };

    // 删除弹窗
    private delVisible = false;
    private delModalData = {
        visible: false,
        list: [],
    };

    factorListClass: any[] = [];
    showDetail: string = '1';
    tableData2: any[] = [];

    tableConfig2: TableConfigVO = {
        rowKey: 'classID', // 主键key
    };

    columns: ColumnVO[] = [
        {
            type: 'checkbox',
            align: 'center',
            width: 60,
        },
        {
            title: '名称',
            field: 'className',
        },
        {
            title: '所属层级',
            field: 'parentClassName',
            render: (value) => (value || '自定义分类'),
        },
        {
            title: '展示顺序',
            field: 'order',
        },
        {
            title: '操作',
            field: 'operation',
            align: 'center',
        },
    ];

    rowData = {
        className: '',
        order: '',
        classID: '',
    };

    paging2: PageVO = {
        total: 0,
        currentPage: 1,
        pageSize: 9999,
    };
    RowList: any[] = [];
    delRowList: string[] = [];
    delRowVisible: boolean = false;
    searchClassName: string = '';
    newClassName: string = '';
    newlyVisible: boolean = false;
    checkRowKeys: string[] = [];
    editVisible: boolean = false;
    checkRowKeysName = [];
    classLevel = '';

    private columns3: any[] = [
        {
            label: '编码',
            prop: 'entryCalculateFactorCode',
            width: 80,
            fun: null,
        },
        {
            label: '名称',
            prop: 'entryCalculateFactorName',
            width: null,
            fun: null,
        },
    ];
    private visibleTemp = false;
    selected: any[] = [];

    // 作用范围
    private riskCalTypePojo = {
        0: '产品-静态',
        1: '产品-指令',
        2: '产品-委托',
        3: '资产单元-静态',
        4: '资产单元-指令',
        5: '资产单元-委托',
        6: '投资组合-静态',
        7: '投资组合-指令',
        8: '投资组合-委托',
    };

    // 表格分页
    private get getCurrentPageTableData() {
        return getCurrentPageData(this.tableData, this.paging.currentPage, this.paging.pageSize);
    }

    // 搜索
    onSearch(data) {
        this.searchParam = data;
        this.paging.currentPage = 1;
        const searchTableData = this.filterTableData(this.tableDataCache);
        this.tableData = searchTableData;
        this.paging.total = searchTableData.length;
    }

    /**
     * 获取因子层级关系
     */
    getFactorTree(): void {
        this.$axios({ method: 'get', url: '/original/factor/listClass' }).then((res: any) => {
            if (res) {
                this.factorListClass = res;
                this.treeData[0].children[2].children = this.factorListClass;
            }
        });
    }

    /**
     * 左边点击节点
     * @param data 节点数据
     * @param refresh 是否强制刷新
     * @param currentPage 当前页
     * @param reset 是否重置搜索条件和选中项，默认是
     */
    clickLeftNode(data, refresh = false, currentPage, reset = true) {
        if (refresh || data.id !== this.selectedNode.id) {
            this.selectedNode.label = data.label;
            this.selectedNode.id = data.id;
            this.checkRowKeys = [];
            if (reset) {
                // 清空选中项
                this.tableSelectedList = [];
                // 清空搜索条件
                this.searchParam = {
                    entryCalculateFactorCode: '',
                    entryCalculateFactorName: '',
                    changeType: '',
                    riskCalType: '',
                    validSymbol: '',
                    entryType: '',
                };
                this.searchClassName = '';
            }
            this.paging.currentPage = currentPage;

            this.loading = true;
            // 请求数据
            if (this.selectedNode.id === '-1' || this.selectedNode.id === '0' || this.selectedNode.id === '1') {
                this.classLevel = '';
                this.showDetail = '1';
                getFactorListByPs(this.selectedNode.id)
                    .then(res => {
                        if (res) {
                            res.forEach(item => {
                                item.key = item.entryCalculateFactorCode;

                                let riskCalTypesText = '';
                                let riskCalTypes = item.riskCalTypes || '';
                                for (let i = 0; i < riskCalTypes.length; i++) {
                                    riskCalTypesText += this.riskCalTypePojo[riskCalTypes[i]] + ',';
                                }
                                item.riskCalTypesText = riskCalTypesText;

                                let changeTypeText = '';
                                for (let i = 0; i < item.changeType.length; i++) {
                                    let changeName = DictionConstUtil.CalFactorChangeType[item.changeType[i]];
                                    changeTypeText += (this.isEmpty(changeName) ? '没有变动' : changeName) + ',';
                                }
                                item.changeTypeText = changeTypeText;

                                let entryTypesText = '';
                                for (let i = 0; i < item.entryTypes.length; i++) {
                                    entryTypesText += DictionConstUtil.EntryType[item.entryTypes[i]] + ',';
                                }
                                item.entryTypesText = entryTypesText;
                            });
                            res.sort((b, a) => a.entryCalculateFactorCode.replace(/[^0-9]/gi, '') - b.entryCalculateFactorCode.replace(/[^0-9]/gi, ''));
                            this.tableDataCache = JSON.parse(JSON.stringify(res));
                            this.tableData = this.filterTableData(this.tableDataCache);
                            this.paging.total = this.tableData.length;
                        } else {
                            this.paging.total = 0;
                            this.tableDataCache = [];
                            this.tableData = [];
                        }
                    })
                    .catch(() => {
                        this.paging.total = 0;
                        this.tableDataCache = [];
                        this.tableData = [];
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            } else if (this.selectedNode.id === '2') {
                this.showDetail = '2';
                this.classLevel = '';
                this.getListClassByName();
            } else {
                this.showDetail = '3';
                this.classLevel = data.level;
                this.getScendFactor();
            }
        }
    }

    getListClassByName() {
        this.$axios({ method: 'post', url: '/original/factor/listClassByName', data: { className: this.searchClassName } }).then((res: any) => {
            this.tableData2 = res;
            this.paging2.total = res.length || 0;
        });
    }

    getScendFactor() {
        let data = { paging: { currentPage: 1, pageSize: 0 }, parentClassID: this.selectedNode.id.toString() };
        this.$axios({ method: 'post', url: '/original/factor/factorList', data })
            .then((result: any) => {
                let res = result.list || [];
                if (res) {
                    res.forEach((item) => {
                        item.key = item.entryCalculateFactorCode;

                        let riskCalTypesText = '';
                        let riskCalTypes = item.riskCalTypes || '';
                        for (let i = 0; i < riskCalTypes.length; i++) {
                            riskCalTypesText += this.riskCalTypePojo[riskCalTypes[i]] + (riskCalTypes.length == i + 1 ? '' : ',');
                        }
                        item.riskCalTypesText = riskCalTypesText;

                        let changeTypeText = '';
                        for (let i = 0; i < item.changeType.length; i++) {
                            let changeName = DictionConstUtil.CalFactorChangeType[item.changeType[i]];
                            changeTypeText += (this.isEmpty(changeName) ? '没有变动' : changeName) + (item.changeType.length == i + 1 ? '' : ',');
                        }
                        item.changeTypeText = changeTypeText;

                        let entryTypesText = '';
                        for (let i = 0; i < item.entryTypes.length; i++) {
                            entryTypesText += DictionConstUtil.EntryType[item.entryTypes[i]] + (item.entryTypes.length == i + 1 ? '' : ',');
                        }
                        item.entryTypesText = entryTypesText;
                    });
                    res.sort((b, a) => a.entryCalculateFactorCode.replace(/[^0-9]/gi, '') - b.entryCalculateFactorCode.replace(/[^0-9]/gi, ''));
                    this.tableDataCache = JSON.parse(JSON.stringify(res));
                    this.tableData = this.filterTableData(this.tableDataCache);
                    this.paging.total = this.tableData.length;
                } else {
                    this.paging.total = 0;
                    this.tableDataCache = [];
                    this.tableData = [];
                }
            })
            .catch(() => {
                this.paging.total = 0;
                this.tableDataCache = [];
                this.tableData = [];
            })
            .finally(() => {
                this.loading = false;
            });
            this.tableData = [{}]; // ---
    }

    // 全选方法
    dropdownClick(command) {
        if (command === 'all') {
            this.tableSelectedList = this.tableData.map(item => item.key);
        } else if (command === 'current') {
            let tableSelectedList = this.tableSelectedList;
            this.getCurrentPageTableData.forEach(item => {
                if (!tableSelectedList.includes(item.key)) {
                    tableSelectedList.push(item.key);
                }
            });
        }
    }

    // 搜索方法
    filterTableData(tableDataCache: any[]) {
        let { entryCalculateFactorCode, entryCalculateFactorName, changeType, riskCalType, validSymbol, entryType } = this.searchParam;

        entryCalculateFactorCode = entryCalculateFactorCode.trim();
        entryCalculateFactorName = entryCalculateFactorName.trim();
        const result = tableDataCache
            .filter(item => {
                if (!entryCalculateFactorCode) {
                    return true;
                } else {
                    return item.entryCalculateFactorCode.indexOf(entryCalculateFactorCode) > -1;
                }
            })
            .filter(item => {
                if (!entryCalculateFactorName) {
                    return true;
                } else {
                    return item.entryCalculateFactorName.indexOf(entryCalculateFactorName) > -1;
                }
            })
            .filter(item => {
                if (!changeType) {
                    return true;
                } else {
                    return item.changeType === changeType;
                }
            })
            .filter(item => {
                if (!riskCalType) {
                    return true;
                } else {
                    return item.riskCalTypes.includes(riskCalType);
                }
            })
            .filter(item => {
                if (!validSymbol) {
                    return true;
                } else {
                    return item.validSymbol === validSymbol;
                }
            })
            .filter(item => {
                if (!entryType) {
                    return true;
                } else {
                    return item.entryTypes.includes(entryType);
                }
            });

        return result;
    }

    // 翻页功能
    currentChange() {

    }

    currentChange2(val: number) {
        this.paging2.currentPage = val;
    }

    // 禁用弹窗 - 检验是否要禁用
    onOpenDisabled() {
        // 所有可选择的列表
        const ableList = this.tableDataCache.filter(item => item.validSymbol === '1').map(item => item.key);
        // 筛选过后的列表
        const selectedList = this.tableSelectedList.filter(item => ableList.includes(item));

        if (!this.tableSelectedList.length) {
            this.yh_message_error('未选择计算因子');
            return;
        } else if (!selectedList.length) {
            this.yh_message_error('选择的计算因子已是禁用状态');
            return;
        }

        checkBoundOrFactorIsUsed(1, this.tableSelectedList).then(res => {
            if (res && res.length > 0) {
                this.yh_message_error(`选择的计算因子在条目中正在使用!`);
                this.tableSelectedList = [];
            } else {
                this.disabledVisible = true;
                this.disabledModalData.list = selectedList;
            }
        });
    }

    // 禁用弹窗 - 成功回调
    disabledOnSubmit() {
        this.tableSelectedList = [];
        this.clickLeftNode(this.selectedNode, true, this.paging.currentPage, false);
    }

    // 启用弹窗 - 打开
    onOpenEnable() {
        // 所有可选择的列表
        const ableList = this.tableDataCache.filter(item => item.validSymbol !== '1').map(item => item.key);
        // 筛选过后的列表
        const selectedList = this.tableSelectedList.filter(item => ableList.includes(item));

        if (!this.tableSelectedList.length) {
            this.yh_message_error('未选择计算因子');
            return;
        } else if (!selectedList.length) {
            this.yh_message_error('选择的计算因子已是启用状态');
            return;
        }
        this.enableVisible = true;
        this.enableModalData.list = selectedList;
    }

    // 启用弹窗 - 成功回调
    enableOnSubmit() {
        this.tableSelectedList = [];
        this.clickLeftNode(this.selectedNode, true, this.paging.currentPage, false);
    }

    // 删除弹窗 - 检验是否要删除
    onOpenDelModal() {
        // 筛选过后的列表
        const selectedList = [...this.tableSelectedList];

        if (!this.tableSelectedList.length) {
            this.yh_message_error('未选择计算因子');
            return;
        }

        checkBoundOrFactorIsUsed(1, this.tableSelectedList).then(res => {
            if (res && res.length > 0) {
                this.yh_message_error(`选择的计算因子在条目中正在使用!`);
                this.tableSelectedList = [];
            } else {
                this.delVisible = true;
                this.delModalData.list = selectedList;
            }
        });
    }
    // 删除弹窗 - 成功回调
    delOnSubmit() {
        this.tableSelectedList = [];
        this.clickLeftNode(this.selectedNode, true, 1, false);
    }

    delRows() {
        this.checkRowKeys = (this.$refs['risk-table'] as VueObject).checkRowKeys;
        if (!this.checkRowKeys.length) {
            this.yh_message_warn('请选择分类!');
            return;
        }
        if ((this.checkRowKeys as any).includes(3)) {
            this.yh_message_warn('其他指标分类不可删除!');
            return;
        }
        this.checkRowKeysName = [];
        this.checkRowKeys.forEach((item) => {
            this.tableData2.forEach((item2) => {
                if (item2.classID == item) {
                    this.checkRowKeysName.push(item2.className);
                }
            });
        });

        this.delRowVisible = true;
    }

    handleAddNewly() {
        if (this.newClassName == '') {
            this.yh_message_warn('分类名称不能为空!')
            return
        }
        let data = { className: this.newClassName, parentClassID: this.selectedNode.id };
        this.$axios({ method: 'post', url: '/original/factor/insertFactorClass', data }).then((res: any) => {
            this.newlyVisible = false;
            this.newClassName = '';
            this.yh_message_success('新增成功');
            this.getListClassByName();
            this.getFactorTree();
        });
    }
    handleEditNewly() {
        if (this.rowData.className == '') {
            this.yh_message_warn('分类名称不能为空!')
            return
        }
        this.$axios({
            method: 'post',
            url: '/original/factor/updateFactorClassName',
            data: {
                classID: this.rowData.classID,
                className: this.rowData.className,
                order: this.rowData.order,
            },
        }).then((res: any) => {
            this.editVisible = false;
            this.yh_message_success('编辑成功');
            this.getListClassByName();
            this.getFactorTree();
            this.rowData.className = '';
            this.rowData.order = '';
            this.rowData.classID = '';
        });
    }
    handleDelRow() {
        // let data = this.RowList.map((item) => item.classID);
        let data = this.checkRowKeys;
        this.$axios({ method: 'post', url: '/original/factor/deleteFactorClass', data }).then((res: any) => {
            this.delRowVisible = false;
            // this.RowList = [];
            // this.delRowList = [];
            this.$nextTick(() => {
                (this.$refs['risk-table'] as VueObject).resetCheckRowKeys();
            });
            this.yh_message_success('删除成功');
            this.getListClassByName();
            this.getFactorTree();
        });
    }

    editRow(row) {
        this.editVisible = true;
        this.rowData.className = row.className;
        this.rowData.order = row.order;
        this.rowData.classID = row.classID;
    }

    delRow(row) {
        // this.RowList = [row];
        // this.delRowList = [row.className];
        this.checkRowKeysName = [];
        this.checkRowKeys = [row.classID];
        this.checkRowKeysName = [row.className];
        this.delRowVisible = true;
    }

    handleEdit() {
        this.selected = this.tableData;
        this.visibleTemp = true;
    }

    onSubmit() {
        let dom = this.$refs['trans'] as any;
        let removeCodeList = this.getRemoveCodeList(this.tableData, dom.getRightAllData());
        let data = { classID: this.selectedNode.id, codeList: dom.getRightAllData().map((i) => i.entryCalculateFactorCode), removeCodeList };
        this.$axios({ method: 'post', url: '/original/factor/moveFactorToClass', data }).then((res: any) => {
            this.yh_message_success('修改成功');
            this.visibleTemp = false;
            this.getScendFactor();
        });
    }

    getRemoveCodeList(oldData, newData) {
        let oldList = oldData.map((i) => i.entryCalculateFactorCode);
        let newList = newData.map((i) => i.entryCalculateFactorCode);

        let deletedValues = oldList.filter((value) => {
            return !newList.includes(value);
        });
        return deletedValues;
    }

    // 下载文件
    exportFile(type: string) {
        // if (['json', 'pdf'].includes(type) && !this.tableSelectedList.length) {
        //     this.yh_message_error('未选中导出数据');
        //     return;
        // }
        if (type === 'json') {
            exportFactorToJson({ codes: this.tableSelectedList });
        } else if (type === 'pdf') {
            exportFactorToPDF({ codes: this.tableSelectedList });
        } else if (type === 'sql') {
            this.openExportModal();
        }
    }

    // 下载文件弹窗数据
    exportVisible = false;
    exportModalData = {
        list: [],
    };

    // 下载文件弹窗 - 列表
    openExportModal() {
        const tableSelectedList = this.tableSelectedList;
        const tableDataCache = this.tableDataCache;
        this.exportModalData.list = tableDataCache.filter(item => {
            return tableSelectedList.includes(item.key);
        });
        this.exportVisible = true;
    }
    // 导出sql回调
    exportSqlOnSubmit() {}

    // 标签操作
    handleTabs(type, row) {
        if (type === 'add') {
            this.dispatch('CalculateFactor', 'handleTags', { type: 'add' });
        } else {
            this.dispatch('CalculateFactor', 'handleTags', { type: type, code: row.entryCalculateFactorCode });
        }
    }

    private showSourceModal = false; // 数据源设置弹窗

    private sourceCode = ''; // 数据源设置编号

    private startFlag: boolean = false; // 是否可配置

    private opType: string = '';

    // 打开数据源设置
    openDataSource(row: any) {
        if (row.validSymbol === '1') {
            this.startFlag = true;
        }
        this.showSourceModal = true;
        this.sourceCode = row.entryCalculateFactorCode;
    }

    // 数据源设置回调
    sourceOnSubmit() {
        if (this.startFlag) {
            this.startFlag = false;
            this.showSourceModal = false;
            // this.selectedRowKeys = [];
            // this.selectedRows = [];
            // this.showStartModal = false;
            this.clickLeftNode(this.selectedNode, true, 1, false);
            return;
        }
    }

    isEmpty(obj) {
        return typeof obj == 'undefined' || obj == null || obj === '';
    }
}
</script>

<style lang="scss" scoped>
@import '../../../assets/style/layout01';
</style>
